package cn.dida.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.dida.core.SysresMap;
import cn.dida.exception.BizzException;
import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.Staff;
import cn.dida.model.Sysres;
import cn.dida.model.SysresExt;
import cn.dida.model.UserSession;
import cn.dida.service.RoleService;
import cn.dida.service.StaffService;
/**
 * <p>账户管理</p>
 * @author weiwei
 * */
@Controller
public class AuthorizationController extends BaseController {
    /*@Autowired
    private SysresService sysresService;*/
    @Autowired
    private StaffService staffService;
	@Autowired
	private RoleService roleService;

    /**
     * 打开权限设置页面
     * @param staffId 账户id
     * @return ModelAndView
     * */
    @GetMapping("/authorize/{staffId}")
    public ModelAndView sysres(HttpServletRequest request, @PathVariable Integer staffId) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        Staff staff = staffService.getStaff(userSession.getCompanyId(), staffId);

        if (staff.getAdmin()) {
            throw new BizzException(BizzException.error_code_invalid_request, "无法给管理员设置权限");
        }

        
    	List<Sysres> roleResList = roleService.getRoleSysresByCompanyId(staff.getCompanyId());

        

        //操作人员的权限树
        List<Sysres> operatorOwnedResList = new ArrayList<>();
        if (userSession.getAdmin()) {
            operatorOwnedResList.addAll(roleResList);
        } else {
            if (StringUtils.isNotEmpty(userSession.getResIds())) {
                ArrayList<Sysres> tmp = new ArrayList<>();
                List<String> staffResIdList = Arrays.asList(StringUtils.split(userSession.getResIds(), ","));
                for (Sysres resNode : roleResList) {
                    if (staffResIdList.contains(resNode.getId().toString())) {
                        tmp.add(resNode);
                    }
                }
                operatorOwnedResList.addAll(tmp);
            }
        }


        //标记待分配权限人员拥有的权限
        List<Sysres> targetStaffOwnedResList = new ArrayList<>();
        if (staff.getAdmin()) {
            targetStaffOwnedResList.addAll(roleResList);
        } else {
            targetStaffOwnedResList.addAll(staffService.getStaffRes(userSession.getCompanyId(), staffId));
        }


        List<SysresExt> markedResList = new ArrayList<>();
        for (Sysres res1 : operatorOwnedResList) {
            SysresExt sysresExt = new SysresExt(res1);
            for (Sysres res2 : targetStaffOwnedResList) {
                if (sysresExt.getId().intValue() == res2.getId().intValue()) {
                    sysresExt.setMark(true);
                    break;
                }
            }
            markedResList.add(sysresExt);
        }
        

        model.put("staff", staff);
        List<SysresExt> resTree = SysresMap.makeTree(markedResList);
        SysresMap.sort(resTree);
        model.put("resTree", resTree);
        return new ModelAndView("authorize").addAllObjects(model);
    }


    /**
     * 保存or更新权限设置
     * @param staffId 账户id
     * @param authIds 权限id集合
     * @return HttpResponseBodyWrapper
     * */
    @ResponseBody
    @PutMapping("/authorize/{staffId}")
    public HttpResponseBodyWrapper postAuth(HttpServletRequest request, @PathVariable Integer staffId, @RequestBody Integer[] authIds) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);

        Boolean result = staffService.updateStaffAuth(userSession.getCompanyId(), staffId, authIds);
        return new HttpResponseBodyWrapper(result);
    }

}
